package com.atguigu.gmall.order.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.payment.client.PaymentFeignClient;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @author mqx
 * @date 2020-10-24 11:30:43
 */
@Component
public class OrderReceiver {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PaymentFeignClient paymentFeignClient;

    @Autowired
    private RabbitService rabbitService;

    // 监听消息
    /*
    1.  关闭电商模块的订单记录，交易记录
    2.  同时关闭支付宝的交易记录
     */
    @SneakyThrows
    @RabbitListener(queues = MqConst.QUEUE_ORDER_CANCEL)
    public void cancelOrder(Long orderId, Message message, Channel channel){

        // 判断orderId 180
        if (orderId!=null){
            // select * from order_info where id = orderId
            OrderInfo orderInfo = orderService.getById(orderId);
            //  继续判断 orderId = 14 , 订单Id 存储并且订单的状态，进程的状态为UNPAID.
            if (orderInfo!=null && "UNPAID".equals(orderInfo.getOrderStatus()) &&  "UNPAID".equals(orderInfo.getProcessStatus())){
                //  关闭过期订单！
                //  update order_info set OrderStatus = ? and ProcessStatus = ? where id = orderId;
                //  orderService.execExpiredOrder(orderId);
                //  判断电商模块中是否有交易记录
                PaymentInfo paymentInfo = paymentFeignClient.getPaymentInfo(orderInfo.getOutTradeNo());
                //  有交易记录，并且是未付款
                if (paymentInfo!=null && paymentInfo.getPaymentStatus().equals("UNPAID")){
                    //  查看支付宝中是否有交易记录
                    Boolean flag = paymentFeignClient.checkPayment(orderId);
                    if (flag){
                        //  表示有交易记录，说明用户一定扫描了二维码，但是不能确定用户是否付款！
                        Boolean res = paymentFeignClient.closePay(orderId);
                        if (res){
                            //  说明用户未付款，那么关闭电商模块中的交易记录, 订单的关闭！
                            //  orderInfo 有记录，那么paymentInfo 不一定有！   如果paymentInfo 有记录，那么orderInfo 一定有！
                            orderService.execExpiredOrder(orderId,"2");
                        }else {
                            //  说明在即将取消订单的时候，用户付款了。
                            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_PAYMENT_PAY,MqConst.ROUTING_PAYMENT_PAY,orderId);
                        }
                    }else {
                        //  关闭orderInfo， paymentInfo
                        orderService.execExpiredOrder(orderId,"2");
                    }
                }else {
                    //  只关闭orderInfo
                    orderService.execExpiredOrder(orderId,"1");
                }
            }
        }

        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //  监听支付成功后，支付模块发送过来的消息！
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_PAYMENT_PAY,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_PAY),
            key = {MqConst.ROUTING_PAYMENT_PAY}
    ))
    public void updateOrderStatus(Long orderId,Message message,Channel channel){
        //  判断处理
        if (orderId!=null) {
            // 直接更新
            OrderInfo orderInfo = orderService.getById(orderId);
            if (orderInfo != null && "UNPAID".equals(orderInfo.getOrderStatus()) && "UNPAID".equals(orderInfo.getProcessStatus())) {
                //  修改成已支付PAID
                orderService.updateOrderStatus(orderId,ProcessStatus.PAID);
                //  发送消息通知仓库！ Json
                //  1.  构成发送的 Json 字符串。 通过orderId 获取到orderInfo ,然后就可以组成Json 字符串了。
                //  2.  然后发送消息
                orderService.sendOrderStatus(orderId);
                //  orderService.sendOrderStatus(orderInfo); orderInfo中是否有订单明细details:

            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_WARE_ORDER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_ORDER),
            key = {MqConst.ROUTING_WARE_ORDER}
    ))
    public void updateOrderStatusByOrderId(String strJson,Message message,Channel channel){
        //  strJson = {"orderId":"25","status":"DEDUCTED"}
        //  判断处理
        if (!StringUtils.isEmpty(strJson)){
            Map map = JSON.parseObject(strJson, Map.class);
            String orderId = (String) map.get("orderId");
            if ("DEDUCTED".equals(map.get("status"))){
                //  说明减库存成功
                orderService.updateOrderStatus(Long.parseLong(orderId),ProcessStatus.WAITING_DELEVER);
            }else {
                //  减库失败！ 订单-- 支付-- 库存 看作一个整体，由于电商的特性，使用mq 保证数据的最终一致性。
                //  info.log(orderId + "减库存异常，要求补货！" ); 再次发个消息
                orderService.updateOrderStatus(Long.parseLong(orderId),ProcessStatus.STOCK_EXCEPTION);
            }
        }

        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
